package com.atguigu.spzx.manager.service.system.impl;

import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.system.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.AuthContextUtil;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.atguigu.spzx.model.vo.system.ValidateCodeVo;
import com.atguigu.spzx.util.SpzxAssert;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        String userName = loginDto.getUserName();
        String userPassword = loginDto.getPassword(); // 用户输入
        // 判断请求参数不能为空
        SpzxAssert.isTrue(!StringUtils.isEmpty(userName) && !StringUtils.isEmpty(userPassword),"用户名或者密码不能为空");

        String captcha = loginDto.getCaptcha(); // 用户输入的验证码
        String codeKey = loginDto.getCodeKey(); // redis中验证码的数据key
        SpzxAssert.isTrue(!StringUtils.isEmpty(captcha) && !StringUtils.isEmpty(codeKey),"验证码不能为空");
        String serverCaptcha = redisTemplate.opsForValue().get(codeKey);
        SpzxAssert.isTrue(serverCaptcha.equals(captcha),"验证码输入有误");
        // 验证码用用完删除缓存
        redisTemplate.delete(codeKey);

        SysUser sysUser = sysUserMapper.selectSysUserByUsername(userName);
        if (null == sysUser){
            // 用户不存在
            return null;
        }else {
            // 用户存在
            String dbPassword = sysUser.getPassword(); // 数据库密码
            // 对用户输入密码加密
            String md5userPassword = DigestUtils.md5DigestAsHex(userPassword.getBytes());
            SpzxAssert.isTrue(dbPassword.equals(md5userPassword),"密码错误");
           /* if (!dbPassword.equals(md5userPassword)){
                // 密码校验不通过
                return null;
            }*/
            LoginVo loginVo = new LoginVo();
            // 生成令牌
            String token = UUID.randomUUID().toString().replace("-","");
            // 保存到redis中
            redisTemplate.opsForValue().set("user:login:" + token, JSON.toJSONString(sysUser));
            loginVo.setToken(token);
            loginVo.setRefresh_token(token);
            return loginVo;
        }
    }

    @Override
    public SysUser getUserInfo(String token) {
        SysUser user = AuthContextUtil.getUser();
        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
        // 断言方式 校验 如果为空抛出异常
     //   SpzxAssert.notNull(userJson,"用户检验失败");
        // 如果不为空，格式转换
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:" + token);
    }

    @Override
    public ValidateCodeVo generateValidateCode() {
        // k v 图
        String key = UUID.randomUUID().toString().replace("-","");
        CircleCaptcha captcha = new CircleCaptcha(150,48,4,10);
        String value = captcha.getCode();
        String image = captcha.getImageBase64Data();

        // 将k 和v到缓存中
        redisTemplate.opsForValue().set(key,value,5, TimeUnit.MINUTES);

        // 将k和图返回给前端
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(key);
        validateCodeVo.setCodeValue(image);
        return validateCodeVo;
    }

    @Override
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> sysUserList =  sysUserMapper.selectAllSysUser(sysUserDto);
        PageInfo<SysUser> pageInfo = new PageInfo<>(sysUserList);
        return pageInfo;
    }

    @Override
    public void insertSysUser(SysUser sysUser) {
        sysUserMapper.insertSysUser(sysUser);
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public void deleteSysUserById(Long id) {
        sysUserMapper.deleteSysUserById(id);
    }

}
